package gw.com.android.ui.onlive.analyst;

import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gwtsz.gts2.hx.R;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.GTConfig;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.MyConcernRequest;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.me_concern.AnalystData;
import gw.com.android.ui.onlive.component.ActiveButton;
import gw.com.android.ui.views.CommonTitleBar;
import gw.com.android.ui.views.ImageWatcher;
import gw.com.android.utils.PackStatis;
import www.com.library.app.Logger;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.util.DeviceUtil;

/**
 * 分析师的主页
 *
 * @author jett
 * @since 2018-06-04.
 */
public class AnalystActivity extends BaseActivity {

    @BindView(R.id.analyst_root)
    AnalystRootView mRootView;
    @BindView(R.id.analyst_head)
    View viewHead;
    @BindView(R.id.analyst_tabs_bg)
    View viewTabsBg;
    @BindView(R.id.analyst_back)
    View ivBack;
    @BindView(R.id.title_bar)
    CommonTitleBar mTitleBar;
    @BindView(R.id.civ_head)
    ImageView civ_head;
    @BindView(R.id.analyst_name)
    TextView tvName;
    @BindView(R.id.analyst_position)
    TextView tvPosition;
    @BindView(R.id.analyst_winrate)
    TextView tvWinrate;
    @BindView(R.id.analyst_profit)
    TextView tvProfit;
    @BindView(R.id.ll_add_concern)
    ActiveButton ll_add_concern;
    @BindView(R.id.analyst_tabs)
    TabLayout tlTabs;
    @BindView(R.id.analyst_pages)
    ViewPager vpPages;
    @BindView(R.id.analyst_divider)
    View viewDivider;
    @BindView(R.id.v_image_watcher)
    ImageWatcher imageWatcher;//图片放大工具类

    private AnalystRequest.AnalystData mAnalystData;
    private AnalystRequest analystRequest;
    private IntroFragment introFragment;//基本信息
    private PostFragment postFragment;//观点
    private ReplyFragment replyFragment;//点评

    private String[] followedAnalyst = new String[1];//用户关注的分析师
    private MyConcernRequest request = new MyConcernRequest();
    private Context mContext;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_analyst;
    }

    /**
     * 返回按钮监听
     */
    public void onBackPressed() {
        if (imageWatcher != null && imageWatcher.getVisibility() == View.VISIBLE) {
            imageWatcher.handleBackPressed();
        } else {
            finish();
        }
    }

    @Override
    protected void initLayoutView() {
        mContext = AnalystActivity.this;
        imageWatcher = (ImageWatcher) findViewById(R.id.v_image_watcher);
        AnalystAdapter adapter = new AnalystAdapter(getSupportFragmentManager());
        vpPages.setAdapter(adapter);
        vpPages.setCurrentItem(1);//设置默认显示的item
        vpPages.setOffscreenPageLimit(3);//设置子页面缓存量为2（在当前显示界面之外的缓存量）,因为如果不这样做，第三个和第一个fragment就会多次执行onCreateView.
        tlTabs.setupWithViewPager(vpPages);

        int mHeadHeight = (int) (DeviceUtil.instance().dip2px(255 - 13 - 50, this) - getResources().getDimension(R.dimen.toolbar_top_space));
        mRootView.setMaxScrollY(mHeadHeight - 1);
        mRootView.setOnScrollListener(new AnalystRootView.OnScrollListener() {
            @Override
            public void onScrolled(int distance, int scrolled, int max, float percent) {
                onScroll(distance, scrolled, max, percent);
            }
        });
        int radius = DeviceUtil.instance().dip2px(13, getApplication());
        viewTabsBg.setBackgroundDrawable(new TabCornorDrawable(radius));
    }

    private String userNo;//帐户名 (gts2740)
    private String accountNo;// 交易账户名 (60052740)

    @Override
    protected void initViewData() {
        userNo = getIntent().getStringExtra("userNo");//分析师no
        accountNo = getIntent().getStringExtra("accountNo");
        loadCache();
        if (TextUtils.isEmpty(accountNo))// 后台有可能不返回这个，那么 我只能自己去完善了
        {
            Log.d("AnalystActivityTag", "沒有accountNo，我自己来获取accountNo");
            supplementData(userNo);
        } else {
            Log.d("AnalystActivityTag", "有accountNo，直接加载数据");
            realLoadData();
        }
    }

    private void refreshUI(AnalystRequest.AnalystData data) {
        if (data == null) {
            return;
        }
        mAnalystData = data;
        if (!TextUtils.isEmpty(data.avatar)) {
            //取得默认图
            Glide.with(this)
                    .load(data.avatar)
                    .placeholder(R.mipmap.a_def_teacher)
                    .dontAnimate()//防止设置placeholder导致第一次不显示网络图片,只显示默认图片的问题
                    .error(R.mipmap.a_def_teacher)
                    .into(civ_head);
        }
        tvName.setText(TextUtils.isEmpty(data.userName) ? "--" : data.userName);
        mTitleBar.setAppTitle(TextUtils.isEmpty(data.userName) ? "--" : data.userName);
        if (TextUtils.isEmpty(data.position)) {
            tvPosition.setVisibility(View.GONE);
        } else {
            tvPosition.setVisibility(View.VISIBLE);
            tvPosition.setText(data.position);
        }
        tvWinrate.setText(TextUtils.isEmpty(data.winRate) ? "--" : data.winRate);
        tvProfit.setText(TextUtils.isEmpty(data.gain) ? "--" : data.gain);
        if (introFragment != null && !TextUtils.isEmpty(data.introduction)) {
            introFragment.setIntroduction(mAnalystData.introduction);
        }
    }

    @OnClick(R.id.analyst_back)
    public void back() {
        finish();
    }

    /**
     * 页面上下滑动 回调
     */
    private void onScroll(int distance, int scrolled, int max, float percent) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) viewTabsBg.getLayoutParams();
        params.topMargin = -scrolled;
        viewTabsBg.setLayoutParams(params);
        viewHead.setTranslationY(-scrolled / 2);

        viewHead.setAlpha(1 - percent);

        if (percent > 0.5F) {
            percent = (percent - 0.5F) * 2;
            mTitleBar.setAlpha(percent);
            ((TabCornorDrawable) viewTabsBg.getBackground()).setRadiusPercent(1 - percent);
        } else {
            mTitleBar.setAlpha(0);
            ((TabCornorDrawable) viewTabsBg.getBackground()).setRadiusPercent(1);
        }

        if (percent <= 0) {
            viewDivider.setVisibility(View.GONE);
        } else if (percent >= 1) {
            viewDivider.setVisibility(View.VISIBLE);
        }
    }

    /**
     * TabLayout+ViewPager+Fragment，实现可滑动的多tab布局
     */
    private class AnalystAdapter extends FragmentPagerAdapter {

        AnalystAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Log.d("AnalystAdapter", "" + position);// 每一个position位置上的getItem最多只会被调用一次
            switch (position) {
                case 0:
                    if (introFragment == null) {
                        introFragment = new IntroFragment();
                        if (mAnalystData != null && !TextUtils.isEmpty(mAnalystData.introduction)) {
                            introFragment.setIntroduction(mAnalystData.introduction);
                        }
                    }
                    return introFragment;
                case 1:
                    if (postFragment == null) {
                        postFragment = new PostFragment();
                        postFragment.setImageWatcher(imageWatcher);
                        postFragment.setAccountNo(userNo);
                    }
                    return postFragment;
                case 2:
                    if (replyFragment == null) {
                        replyFragment = new ReplyFragment();
                        replyFragment.setImageWatcher(imageWatcher);
                        replyFragment.setAccountNo(userNo);
                    }
                    return replyFragment;
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "简介";
                case 1:
                    return "观点";
                case 2:
                    return "点评";
                default:
                    return "";
            }
        }

    }


    /**
     * 检查是否关注了分析师
     */
    private void checkFollowedAnalyst(final String analystNo) {
        // 进入这个页面之前，先取出我关注的分析师
        request.getFollowedAnalystList(GTConfig.instance().mCurName, new HttpCallback<List<AnalystData>>() {
            @Override
            public void onSuccess(List<AnalystData> result) {
                if (result == null)
                    followedAnalyst = new String[]{};
                else {
                    followedAnalyst = new String[result.size()];
                    int i = 0;
                    for (AnalystData data : result) {
                        followedAnalyst[i] = data.userNo;
                        i++;
                    }
                }
                if (checkIfFollowed(analystNo)) {//如果已关注
                    ll_add_concern.switchToFollowed();// 就把关注按钮变成 已关注
                } else {
                    ll_add_concern.switchToAddFollow();
                }
                ll_add_concern.setOnClickListener(new FollowOnClickListener(ll_add_concern, GTConfig.instance().mCurName, userNo));//并且给按钮设置事件，点击之后可以调用接口进行关注

            }

            @Override
            public void onFailure(Exception e) {
                Logger.d("圈子页面-获取已关注的分析师，失败！");
            }
        });
    }

    /**
     * 检查是否已经关注了该分析师
     *
     * @return true表示已关注，false表示没关注
     */
    private boolean checkIfFollowed(String analystUserNo) {
        boolean res = false;
        for (int i = 0; i < followedAnalyst.length; i++) {
            if (followedAnalyst[i].equals(analystUserNo)) {
                res = true;
                break;
            }
        }
        return res;
    }

    /**
     * +关注、取消关注 按钮的点击事件
     */
    class FollowOnClickListener implements View.OnClickListener {

        private ActiveButton activeButton;
        private String userId;//当前登录用户的no
        private String analystNo;//要关注或者取消关注的分析师NO

        public FollowOnClickListener(ActiveButton activeButton, String userId, String analystNo) {
            this.activeButton = activeButton;
            this.userId = userId;
            this.analystNo = analystNo;
        }

        @Override
        public void onClick(View v) {

            //检测登录状态，如果当前是游客状态，那就説明沒有登录
            boolean ifGuest = GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST;
            if (ifGuest) {
                new ToastPopWindow(mContext, "登录之后才能关注").show();
                return;
            }

            //如果是+关注的状态，那么就调用+关注接口（同时切换成progressing状态），然后根据接口返回值决定是不是要变换到 已关注。
            if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_REAL) {//如果不是真实用户
                new ToastPopWindow(mContext, "真实用户才能关注哦").show();
                return;
            }
            activeButton.switchToProgressBar();
            if (activeButton.getCurrentStatu() == ActiveButton.STATU_ADD_FOLLOW) {// 如果按钮显示的是 +关注
                PackStatis.getToService("clickConcern2", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
                setFollow(userId, analystNo, MyConcernRequest.CONST_ADD_FOLLOW, new HttpCallback<String>() {
                    @Override
                    public void onSuccess(String result) {//如果添加关注成功
                        //请求正常返回了,
                        //来判断返回值是true还是false
                        if ("true".equals(result)) {
                            new ToastPopWindow(mContext, "关注成功").show();
                            activeButton.switchToFollowed();
                        } else {
                            new ToastPopWindow(mContext, "关注失败，请重新关注~").show();
                            activeButton.switchToAddFollow();
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        new ToastPopWindow(mContext, "请求超时，请重新关注~").show();
                        activeButton.switchToAddFollow();
                    }
                });
            } else {// 如果当前显示的是已关注，那么点击之后，就可以取消关注，调用取消关注接口
                PackStatis.getToService("clickConcerned2", PackStatis.EventCategory.CIRCLE.getValue(), null, null);
                setFollow(userId, analystNo, MyConcernRequest.CONST_CANCEL_FOLLOW, new HttpCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        if ("true".equals(result)) {
                            new ToastPopWindow(mContext, "取消成功").show();
                            activeButton.switchToAddFollow();
                        } else {
                            new ToastPopWindow(mContext, "关注失败，请重新关注~").show();
                            activeButton.switchToFollowed();
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        new ToastPopWindow(mContext, "请求超时，请重新取消关注~").show();
                        activeButton.switchToFollowed();
                    }
                });
            }
        }
    }

    private MyConcernRequest myConcernRequest;

    private void setFollow(final String userNo, final String analystNo, int ifFollow, HttpCallback<String> callback) {
        if (myConcernRequest == null) {
            myConcernRequest = new MyConcernRequest();
        }
        myConcernRequest.addOrRemoveFollowedAnalystList(userNo, analystNo, ifFollow, callback);
    }


    /**
     * 由于后台给的有可能只有账户，而没有交易账户，所以需要我把交易账户完善。
     */
    private void supplementData(final String userNo) {
        if (myConcernRequest == null) {
            myConcernRequest = new MyConcernRequest();
        }
        myConcernRequest.getAllAnalystList(new HttpCallback<List<AnalystData>>() {
            @Override
            public void onSuccess(List<AnalystData> result) {
                // 获取成功之后，判断当前用户是不是
                String analystNo = "";
                boolean ifAnalyst = false;
                for (int i = 0; i < result.size(); i++) {
                    if (userNo.equals(result.get(i).userNo)) {// 一旦发现当前用户是分析师，那么直接发起 分析师发帖，isAnalyst为true
                        ifAnalyst = true;
                        analystNo = result.get(i).accountNo;
                        break;
                    }
                }
                if (ifAnalyst)
                    Log.d("getAllAnalystTag2", "分析师大佬");
                else
                    Log.d("getAllAnalystTag2", "普通用户");

                accountNo = analystNo;
                Log.d("AnalystActivityTag2", "userNo:" + userNo + " - accountNo:" + accountNo);
                realLoadData();

            }

            @Override
            public void onFailure(Exception e) {
                Log.d("getAllAnalyst", "Exception:" + e.getLocalizedMessage());
            }
        });
    }

    private void loadCache() {
        if (analystRequest == null) {
            analystRequest = new AnalystRequest();
        }
        AnalystRequest.AnalystData data = analystRequest.fetchLocal(accountNo, userNo);
        refreshUI(data);
    }

    private void realLoadData() {
        analystRequest.getInfo(accountNo, userNo, new HttpCallback<AnalystRequest.AnalystData>() {
            @Override
            public void onSuccess(AnalystRequest.AnalystData result) {
                refreshUI(result);
            }

            @Override
            public void onFailure(Exception e) {
                Logger.e(e);
            }
        });

        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {//  如果没登录
            ll_add_concern.switchToAddFollow();//显示加关注，并且点击之后，提示要先登录
            ll_add_concern.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//如果没有登录，就直接显示+关注，并且点击之后，提示先要登录
                    new ToastPopWindow(AnalystActivity.this, "登录之后才可以关注哦!").show();
                }
            });
        } else {//如果已经登录，那么，就获取当前登录用户的已关注分析师的列表，然后对比，现在的分析师有没有在列表里面，如果在，就显示已关注。如果不在，就显示 +关注。
            checkFollowedAnalyst(userNo);
        }
    }

}
